<template>
  <div class="custom-upload">
    <el-dialog
        title="图片裁剪"
        :visible.sync="showCropper"
        width="50%">
        <vue-cropper
            v-if="showCropper"
            id="corpper"
            ref="cropper"
            :class="{'corpper-warp':showCropper}"
            v-bind="cropper"
            :guides="false"
            @realTime="realTime"
            :autoCropWidth="150"
            :autoCropHeight="150"
        />
        <div>
            <el-button @click="rotateLeft">左旋转</el-button>
            <el-button @click="rotateRight">右旋转</el-button>
            <el-button @click="downImg('blob')">下载图片</el-button>
        </div>
        <div style="width:150px;height:150px;overflow:hidden">
            <div :style="cropper.previews.div" style="overflow:hidden">
            <el-image :style="cropper.previews.img" :src="cropper.previews.url"></el-image>
        </div>
        </div>
        <span slot="footer" class="dialog-footer"  >
            <el-button @click.native="showCropper=false">取 消</el-button>
            <el-button type="primary" :loading="loading" @click="uploadCover">确 定</el-button>
        </span>
        </el-dialog>
    <input
      :id="id"
      type="file"
      style="display: none"
      name="single"
      accept="image/*"
      @change="onChange($event)"
    />

    <el-button size="small" type="primary" :loading="loading" @click="handleOpenFile()">
      <i class="fa fa-upload" />
      {{ buttonName }}
    </el-button>
    <div v-if="tips" class="tips clear-margin-top">{{ tips }}</div>
  </div>
</template>

<script>
// 上传文件组件
import { VueCropper } from 'vue-cropper'

// 定义的接口根据自己项目更换
// import { uploadImage } from '@/api/upload'

import { isImageFile, isMaxFileSize, readFile } from '@/utils/upload'   // 见下文
import { Message } from 'element-ui'

export default {
  components: {
    VueCropper
  },
  props: {
    // 最大上传文件的大小
    maxFileSize: {
      type: Number,
      default: 2 // （MB)
    },
    // 按钮文字
    buttonName: {
      type: String,
      default: '添加图片'
    },
    // 提示内容
    tips: {
      type: String
    },
    // 图片裁剪比列
    fixedNumber: {
      type: Array,
      default: function() {
        return []
      }
    },
    // 图片文件分辨率的宽度
    width: {
      type: Number,
      default: 460
    },
    // 图片文件分辨率的高度
    height: {
      type: Number,
      default: 300
    }
  },
  data() {
    return {
      id: 'cropper-input-' + +new Date(),
      loading: false,
      showCropper: false,
      cropper: {
        img: '',
        info: true,
        size: 0.9,
        outputType: 'png',
        canScale: true,
        autoCrop: true,
        full: true,
        // 只有自动截图开启 宽度高度才生效
        autoCropWidth: this.width,
        autoCropHeight: this.height,
        fixedBox: false,
        // 开启宽度和高度比例
        fixed: true,
        fixedNumber: this.fixedNumber,
        original: false,
        canMoveBox: true,
        canMove: true,
        previews: '' // 实时预览图片
      },
      fileName: '' // 本机文件名
    }
  },
  methods: {
      // 左旋转
      rotateLeft() { 
        console.log('rotateLeft')
        this.$refs.cropper.rotateLeft(); 
      }, 
      // 右旋转
      rotateRight() { 
        console.log('rotateRight')
        this.$refs.cropper.rotateRight(); 
      },
      // 实时预览函数 
      realTime(data) { 
        this.cropper.previews = data 
      },
      // 下载图片
       downImg(type) { 
        console.log('down')
        var aLink = document.createElement('a') 
        aLink.download = 'author-img' 
        if (type === 'blob') { 
          this.$refs.cropper.getCropBlob((data) => { 
            this.downImg = window.URL.createObjectURL(data)
            aLink.href = window.URL.createObjectURL(data) 
            aLink.click() 
          }) 
        } else { 
          this.$refs.cropper.getCropData((data) => { 
            this.downImg = data;
            aLink.href = data; 
            aLink.click() 
          }) 
        } 
      }, 
    // 打开文件
    handleOpenFile() {
      const input = document.getElementById(this.id)
      // 解决同一个文件不能监听的问题
      input.addEventListener(
        'click',
        function() {
          this.value = ''
        },
        false
      )
      // 点击input
      input.click()
    },

    // 裁剪input 监听
    async onChange(e) {
      const file = e.target.files[0]
    this.fileName = file.name;
      if (!file) {
        return Message.error('选择图片失败')
      }
      // 验证文件类型
      if (!isImageFile(file)) {
        return
      }
      try {
        // 读取文件
        const src = await readFile(file)
        this.showCropper = true
        this.cropper.img = src
      } catch (error) {
        console.log(error)
      }
    },

    // 封面上传功能
    uploadCover() {
      this.$refs.cropper.getCropBlob(async imgRes => {
        try {
          // 文件大小限制
          if (!isMaxFileSize(imgRes, this.maxFileSize)) {
            return
          }
          this.loading = true
          console.log(imgRes)
          let formData = new FormData()
          formData.append("file", imgRes, this.fileName);
          console.log(formData)
        //   const url = await uploadImage(imgRes)
        const url = "https://dss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2534506313,1688529724&fm=26&gp=0.jpg"
          this.$emit('subUploadSucceed', url)
          Message.success('上传成功')
          this.loading = false
          this.showCropper = false
        } catch (error) {
          this.loading = false
          this.showCropper = false
          Message.error(error.data.message)
        }
      })
    }
  }
}
</script>

<style lang="scss"  >
#corpper {
  width: 90%;
  height: 400px;
  margin: 0 auto;
  background-image: url();
  z-index: 1002;
}
.cropper-modal {
  background-color: rgba(0, 0, 0, 0.5) !important;
}
.custom-upload {
  .tips {
    margin-top: 10px;
    color: red;
    font-size: 12px;
  }
  .clear-margin-top {
    margin-top: 0;
  }
}
</style>